<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Api;

use App\Models\User;
use Exception;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Validator;

class BaseApi extends BaseController
{
    use AuthorizesRequests;
    use DispatchesJobs;
    use ValidatesRequests;

    /**
     * @var Request
     */
    protected static $request;

    /**
     * Controller constructor.
     * @param $request
     */
    public function __construct(Request $request)
    {
        self::$request = $request;
    }

    /**
     * 数据.
     * @param mixed ...$rule
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|Request
     */
    public static function validate(...$rule)
    {
        $validate = Validator::make(self::$request->all(), ...$rule);
        if ($validate->fails()) {
            header('Content-type:application/json');
            header('Access-control-allow-origin:*');

            exit(responses($validate->errors(), 7)->content());
        }
        return self::$request;
    }

    public static function UserId()
    {
        if (self::$request->USER_ID) {
            return self::$request->USER_ID;
        }
        try {
            $usertoken = decrypt(self::$request->header('token'));
            return $usertoken['id'];
        } catch (Exception $exception) {
            return null;
        }
    }

    public static function UserModel($with = false)
    {
        return User::query()->when($with, function ($query, $value) {$query->with($value); })->find(self::$request->USER_ID);
    }

    public function generateToken(User $user): string
    {
        return encrypt([
            'id' => $user->id,
            'time' => time(),
        ]);
    }

    public function transaction_password($user)
    {
        if (blank($user->transaction_password) || ! password_verify(request('transaction_password'), $user->transaction_password)) {
            $this->exit('交易密码错误或未设置！', 7);
        }
    }

    public function exit($msg, $code = 101)
    {
        header('Content-type:application/json');
        header('Access-control-allow-origin:*');

        exit(responses($msg, $code)->content());
    }
}
